// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (C) 2022 SUSE LLC <mdoucha@suse.cz>
 */

/*\
 * Test for CVE-2022-4378 fixed in kernel v6.1:
 * bce9332220bd ("proc: proc_skip_spaces() shouldn't think it is working on C strings").
 *
 * Check that writing several pages worth of whitespace into /proc/sys files
 * does not cause kernel stack overflow.
 */

#include <stdlib.h>
#include "tst_test.h"

static char *buf;
static unsigned int bufsize;
static int fd = -1;

static struct testcase {
	const char *path;
	int err;
} testcase_list[] = {
	{"/proc/sys/net/ipv4/icmp_ratelimit", EINVAL},
	{"/proc/sys/net/ipv4/icmp_ratemask", EINVAL},
	{"/proc/sys/net/ipv4/icmp_echo_ignore_all", EINVAL},
	{"/proc/sys/net/ipv4/tcp_probe_interval", EINVAL},
	{"/proc/sys/net/ipv4/tcp_keepalive_time", EINVAL},
	{"/proc/sys/net/ipv4/tcp_notsent_lowat", EINVAL},
	{"/proc/sys/net/ipv4/ip_local_reserved_ports", 0}
};

static void setup(void)
{
	tst_setup_netns();

	bufsize = 2 * SAFE_SYSCONF(_SC_PAGESIZE);
	buf = SAFE_MALLOC(bufsize);
	memset(buf, '\n', bufsize);
}

static void run(unsigned int n)
{
	const struct testcase *tc = testcase_list + n;

	if (access(tc->path, W_OK)) {
		tst_res(TCONF | TERRNO, "Skipping %s", tc->path);
		return;
	}

	tst_res(TINFO, "Writing whitespace to %s", tc->path);

	fd = SAFE_OPEN(tc->path, O_WRONLY);
	TEST(write(fd, buf, bufsize));
	SAFE_CLOSE(fd);

	if (TST_RET >= 0 && tc->err == 0) {
		tst_res(TPASS, "write() passed as expected");
	} else if (TST_RET >= 0) {
		tst_res(TFAIL, "write() unexpectedly passed");
	} else if (TST_RET != -1) {
		tst_res(TFAIL | TTERRNO, "Invalid write() return value %ld",
			TST_RET);
	} else if (TST_ERR != tc->err) {
		tst_res(TFAIL | TTERRNO, "write() returned unexpected error");
	} else {
		tst_res(TPASS | TTERRNO, "write() failed as expected");
	}

	if (tst_taint_check())
		tst_res(TFAIL, "Kernel is vulnerable");
}

static void cleanup(void)
{
	if (fd >= 0)
		SAFE_CLOSE(fd);

	if (buf)
		free(buf);
}

static struct tst_test test = {
	.test = run,
	.tcnt = ARRAY_SIZE(testcase_list),
	.setup = setup,
	.cleanup = cleanup,
	.taint_check = TST_TAINT_W | TST_TAINT_D,
	.needs_kconfigs = (const char *[]) {
		"CONFIG_USER_NS=y",
		"CONFIG_NET_NS=y",
		NULL
	},
	.save_restore = (const struct tst_path_val[]) {
		{"/proc/sys/user/max_user_namespaces", "1024", TST_SR_SKIP},
		{}
	},
	.tags = (const struct tst_tag[]) {
		{"linux-git", "bce9332220bd"},
		{"CVE", "2022-4378"},
		{}
	}
};
